package org.eiahe.hr.filler;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.system.domain.HrEmployee;
import org.ehe.system.mapper.HrEmployeeMapper;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
 * 填充员工姓名
 * @author :zhangnn
 * @className :EmployeeNameFiller
 * @description: TODO
 * @date 2025-11-20 15:18:59
 */
@Component
@RequiredArgsConstructor
public class EmployeeNameFiller {

    private final HrEmployeeMapper employeeMapper;

    /**
     * 通用员工姓名填充方法
     *
     * @param list              待填充的数据列表
     * @param employeeNoGetter  获取员工工号的函数
     * @param employeeNameSetter 设置员工姓名的函数
     * @param <T>               列表元素类型
     */
    public <T> void fillEmployeeNames(List<T> list,
                                      Function<T, String> employeeNoGetter,
                                      BiConsumer<T, String> employeeNameSetter) {
        if (CollUtil.isEmpty(list) || employeeNoGetter == null || employeeNameSetter == null) {
            return;
        }

        // 收集所有工号
        List<String> employeeNos = list.stream()
            .map(employeeNoGetter)
            .filter(StringUtils::isNotBlank)
            .distinct()
            .collect(Collectors.toList());

        if (CollUtil.isEmpty(employeeNos)) {
            return;
        }

        // 查询员工信息
        LambdaQueryWrapper<HrEmployee> employeeQuery = Wrappers.lambdaQuery();
        employeeQuery.in(HrEmployee::getEmployeeNo, employeeNos);
        List<HrEmployee> employees = employeeMapper.selectList(employeeQuery);

        // 构建工号到姓名的映射
        Map<String, String> employeeNameMap = employees.stream()
            .collect(Collectors.toMap(HrEmployee::getEmployeeNo, HrEmployee::getEmployeeName));

        // 填充员工姓名
        list.forEach(item -> {
            String employeeNo = employeeNoGetter.apply(item);
            String employeeName = employeeNameMap.get(employeeNo);
            employeeNameSetter.accept(item, employeeName);
        });
    }

    /**
     * 单条数据填充员工姓
     * @param data              待填充的单条实体
     * @param employeeNoGetter  获取员工工号的函数
     * @param employeeNameSetter 设置员工姓名的函数
     * @param <T>               实体类型
     */
    public <T> void fillEmployeeName(T data,
                                     Function<T, String> employeeNoGetter,
                                     BiConsumer<T, String> employeeNameSetter) {
        if (data == null || employeeNoGetter == null || employeeNameSetter == null) {
            return;
        }
        List<T> list = List.of(data);
        fillEmployeeNames(list, employeeNoGetter, employeeNameSetter);
    }

}
